package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xiaotu.common.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.model.MaoYanMovieBasicInfoModel;
import com.xiaotu.common.model.MaoYanSplitBoxofficeDetailModel;
import com.xiaotu.common.model.MaoYanSplitBoxofficeSummaryModel;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

/***
 * 猫眼网剧分账票房明细 （注：当前任务包含  猫眼评分自上映日期至今已达210天的采集）
 * @author Mr.zhang
 *
 */
@Component("MaoYanNetMovieSplitBoxofficeDetailPageProcessor")
public class MaoYanNetMovieSplitBoxofficeDetailPageProcessor extends AUrlPageProcessor {


    protected String resourceSiteId = Constants.SiteName.MAOYAN;//数据来源

    private static String[] START_URL = {"https://www.baidu.com/"};//任意初始请求

    private static String BASICINFO_URL = "https://piaofang.maoyan.com/movie/%s?_v_=yes";//用于获取猫眼评分

    private static String SPLIT_BOXOFFICE_DETAIL_URL = "https://piaofang.maoyan.com/netmovie/%s/allbox";//猫眼分账票房明细

    @Autowired
    private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;

    @Override
    public void process(Page page) {

        Map<String, Object> extrasMap = page.getRequest().getExtras();

        switch (this.getPageDataType(page)) {
            case "/allbox":
                this.splitBoxofficeDetailProcess(page, extrasMap);
                break;
            case "_v_=yes":
                this.maoYanScoreProcess(page, extrasMap);
                break;
            default:
                this.addRequestProcess(page);
                break;
        }

    }


    //获取猫眼评分
    private void maoYanScoreProcess(Page page, Map<String, Object> extrasMap) {

        String url = page.getRequest().getUrl();

        String tvName = extrasMap.get("tvName").toString();

        String dataId = extrasMap.get("dataId").toString();

        if (url.contains(dataId)) {
            String score = page.getHtml().xpath("//div[@class='rating-stars']//span[@class='rating-num']//text()").get();
            MaoYanSplitBoxofficeSummaryModel summaryModel = new MaoYanSplitBoxofficeSummaryModel(
                    UUIDUtils.getId(),
                    null,
                    dataId,
                    tvName,
                    resourceSiteId,
                    null,
                    null,
                    null,
                    score,
                    System.currentTimeMillis()
            );

            //保存
            page.putField(MaoYanSplitBoxofficeSummaryModel.class.getName(), summaryModel);
        }
    }

    //网大分账票房明细
    private void splitBoxofficeDetailProcess(Page page, Map<String, Object> extrasMap) {

        String url = page.getRequest().getUrl();

        String tvName = extrasMap.get("tvName").toString();

        String dataId = extrasMap.get("dataId").toString();

        List<MaoYanSplitBoxofficeDetailModel> splitBoxofficeModelList = new ArrayList<MaoYanSplitBoxofficeDetailModel>();

        if (url.contains(dataId)) {
            //分账日期集合
            List<String> dateRowList = page.getHtml().xpath("//div[@class='t-table']"
                    + "//div[@class='t-left']"
                    + "//div[@class='t-row']").all();
            //分账集合
            List<String> splitRowList = page.getHtml().xpath("//div[@class='t-table']"
                    + "//div[@class='t-right t-scroller']"
                    + "//div[@class='t-row']").all();

            //获取标题
            String title = StringUtils.join(page.getHtml().xpath("//div[@class='t-table']" +
                    "//div[@class='t-right t-scroller']" +
                    "//div[@class='t-header']//div[@class='t-col']//text()").all(), SepratorUtil.SEP_COMMA_EN);

            //分账日期
            String splitBoxDate = null;
            //分账票房
            String daySplitBox = null;
            //观影人次
            String dayViewTimes = null;
            if (null != dateRowList && dateRowList.size() > 0
                    && null != splitRowList && splitRowList.size() > 0
                    && dateRowList.size() == splitRowList.size()) {
                for (int i = 0; i < dateRowList.size(); i++) {
                    Html dateRowHtml = new Html(dateRowList.get(i));
                    Html splitRowHtml = new Html(splitRowList.get(i));
                    //分账日期
                    splitBoxDate = dateRowHtml.xpath("//div[@class='t-row']/@data-id").get().trim();
                    //获取分账票房
                    List<String> splitAndviewList = splitRowHtml.xpath("////div[@class='t-row']//div[@class='t-col']//text()").all();
                    if (null != splitAndviewList && splitAndviewList.size() == 2 && title.contains("分账") && title.contains("观影")) {
                        daySplitBox = splitAndviewList.get(0).trim().replace("--", "");
                        dayViewTimes = splitAndviewList.get(1).trim().replace("--", "");
                    } else if (null != splitAndviewList && splitAndviewList.size() == 1 && title.contains("分账")) {
                        daySplitBox = splitAndviewList.get(0).trim().replace("--", "");
                    } else if (null != splitAndviewList && splitAndviewList.size() == 1 && title.contains("观影")) {
                        dayViewTimes = splitAndviewList.get(1).trim().replace("--", "");
                    }


                    MaoYanSplitBoxofficeDetailModel model = new MaoYanSplitBoxofficeDetailModel(
                            UUIDUtils.getId(),
                            null,
                            dataId,
                            tvName,
                            resourceSiteId,
                            StringUtils.isBlank(splitBoxDate) == true ? null : splitBoxDate,
                            StringUtils.isBlank(daySplitBox) == true ? null : daySplitBox,
                            StringUtils.isBlank(dayViewTimes) == true ? null : dayViewTimes,
                            System.currentTimeMillis()
                    );

                    splitBoxofficeModelList.add(model);

                }
            }
            //保存
            page.putField(MaoYanSplitBoxofficeDetailModel.class.getName(), splitBoxofficeModelList);
        }

    }


    //添加爬取任务
    protected void addRequestProcess(Page page) {

        //猫眼分账票房明细(暂时无法爬取)
//        List<MaoYanMovieBasicInfoModel> notYetAchievedCycleDateList = maoYanMovieBasicInfoService.queryNotYetAchievedCycleDate();
//
//        for (MaoYanMovieBasicInfoModel obj : notYetAchievedCycleDateList) {
//            Map<String, Object> extraMap = new HashMap<String, Object>();
//            extraMap.put("tvName", obj.getTvname());
//            extraMap.put("dataId", obj.getDataid());
//            extraMap.put("tvType", obj.getTvType());
//            if (null == obj.getDataid() || StringUtils.isBlank(obj.getDataid())) {
//                continue;
//            }
//            PageUtils.addTargetRequest(page, String.format(SPLIT_BOXOFFICE_DETAIL_URL, obj.getDataid()), extraMap);
//        }

        //猫眼评分(上映日期至今已到达210天)
		List<MaoYanMovieBasicInfoModel> arriveYetAchievedCycleDateList = maoYanMovieBasicInfoService.arriveYetAchievedCycleDateList();
		
		for(MaoYanMovieBasicInfoModel obj : arriveYetAchievedCycleDateList){
			Map<String,Object> extraMap = new HashMap<String,Object>();
			extraMap.put("tvName", obj.getTvname());
			extraMap.put("dataId", obj.getDataid());
			extraMap.put("tvType", obj.getTvType());
			if(null == obj.getDataid() || StringUtils.isBlank(obj.getDataid())){
				continue;
			}
			PageUtils.addTargetRequest(page, String.format(BASICINFO_URL, obj.getDataid()), extraMap);
		}


    }


    @Override
    protected String[] getStartRequestUrls() {
        return START_URL;
    }

    @Override
    protected String getSpiderType() {
        return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
    }

    @Override
    public String getPageDataType(Page page) {
        String url = page.getUrl().toString();
        if (url.contains("/allbox")) {
            return "/allbox";
        } else if (url.contains("_v_=yes")) {
            return "_v_=yes";
        }
        return "addRequest";
    }

}
